package com.waijiaojun.tpo.service;

import com.aliyun.oss.model.ObjectMetadata;
import com.waijiaojun.tpo.entity.Scenario;
import com.waijiaojun.tpo.exception.ServerException;
import com.waijiaojun.tpo.repository.ScenarioDao;
import com.waijiaojun.tpo.utils.AliyunOssUtil;
import com.waijiaojun.tpo.utils.Constants;
import com.waijiaojun.tpo.utils.HttpUtil;
import com.waijiaojun.tpo.utils.Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.imgscalr.Scalr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * Created by Peter on 2018/3/12.
 */
@Service
public class DowloadResoursesToOssService {
    private static Logger logger = LoggerFactory.getLogger(DowloadResoursesToOssService.class);

    @Resource
    private ScenarioDao scenarioDao;

    public void downloadArticleAudio() throws UnsupportedEncodingException {
        List<Scenario> list = scenarioDao.findAllScenario();

//        Scenario scenario = list.get(0);

        for(Scenario scenario:list) {
            String audioUrl = scenario.getAudioUrl();
            logger.info("\n\n Start 下载 url for id ["+scenario.getId()+"]:" + audioUrl);
            String pathName = null;

            if (StringUtils.isNotBlank(audioUrl) && audioUrl.startsWith("http") && !audioUrl.contains("file.waijiaojun.com")) {
                audioUrl = audioUrl.replaceAll(" ","%20");
                try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                    HttpGet post = new HttpGet(audioUrl);
                    CloseableHttpResponse response = httpclient.execute(post);
                    logger.info("Executed response " + response.getStatusLine().toString());
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        InputStream responseBody = entity.getContent();
                        Long length = entity.getContentLength();
                        try {
                            String suffix = getSuffix(audioUrl);
                            pathName = Constants.ossRootDir + "article/" + scenario.getId() + "/" + scenario.getId() + "_" + UUID.randomUUID().toString() + suffix;
                            ObjectMetadata objectMetadata = new ObjectMetadata();
                            objectMetadata.setContentLength(length);

                            logger.info(" upload file to oss \n bucketName:" + Constants.ossBucketName + "\n key:" + pathName + "\n size:" + length);
                            AliyunOssUtil.client.putObject(Constants.ossBucketName, pathName, responseBody, objectMetadata);

                            scenarioDao.updateAudioUrlForOss(scenario.getId(), Util.toFullOssUrl(pathName), audioUrl);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                            throw new ServerException("上传到OSS失败");
                        }

                        logger.info("新的audioUrl -->>" + Util.toFullOssUrl(pathName));
                    } else {
                        logger.error("Response entity is null.");
                    }
                } catch (Exception e) {
                    logger.error("读取网络资源Error", e);
                    throw new ServerException("读取网络资源Error");
                }
            } else {
                logger.info("不用下载 url:" + audioUrl);
            }
            logger.info("\n 下载 end url:" + audioUrl + "-------------------------------------------------- end");
        }
    }

    public void downloadArticleCover() throws UnsupportedEncodingException {
        List<Scenario> list = scenarioDao.findAllScenario();

        for(Scenario scenario:list) {
            String coverUrl = scenario.getCoverUrl();
            logger.info("\n\n Start 下载 url for id ["+scenario.getId()+"]:" + coverUrl);
            String pathName = null;

            if (StringUtils.isNotBlank(coverUrl) && coverUrl.startsWith("http") && !coverUrl.contains("file.waijiaojun.com")) {
                coverUrl = coverUrl.replaceAll(" ","%20");
                try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                    HttpGet post = new HttpGet(coverUrl);
                    CloseableHttpResponse response = httpclient.execute(post);
                    logger.info("Executed response " + response.getStatusLine().toString());
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        InputStream responseBody = entity.getContent();
                        Long length = entity.getContentLength();
                        try {
                            String suffix = getSuffixForCoverUrl(coverUrl);
                            pathName = Constants.ossRootDir + "article/" + scenario.getId() + "/" + scenario.getId() + "_" + UUID.randomUUID().toString() + suffix;
                            ObjectMetadata objectMetadata = new ObjectMetadata();
                            objectMetadata.setContentLength(length);

                            logger.info(" upload file to oss \n bucketName:" + Constants.ossBucketName + "\n key:" + pathName + "\n size:" + length);
                            AliyunOssUtil.client.putObject(Constants.ossBucketName, pathName, responseBody, objectMetadata);

                            scenarioDao.updateCoverUrlForOss(scenario.getId(), Util.toFullOssUrl(pathName), coverUrl);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                            throw new ServerException("上传到OSS失败");
                        }

                        logger.info("新的audioUrl -->>" + Util.toFullOssUrl(pathName));
                    } else {
                        logger.error("Response entity is null.");
                    }
                } catch (Exception e) {
                    logger.error("读取网络资源Error", e);
                    throw new ServerException("读取网络资源Error");
                }
            } else {
                logger.info("不用下载 url:" + coverUrl);
            }
            logger.info("\n 下载 end url:" + coverUrl + "-------------------------------------------------- end");
        }
    }

    private String getSuffixForCoverUrl(String coverUrl) {

        String suffix = coverUrl.substring(coverUrl.lastIndexOf("."),coverUrl.lastIndexOf("?")).trim().replaceAll(" ","");
        return suffix;
    }

    private static String getSuffix(String audioUrl) {
        String suffix = audioUrl.substring(audioUrl.lastIndexOf("."));
        return suffix;
    }

    public static void main(String[] args) {
        String audioUrl = "https://tikustorage.oss-cn-hangzhou.aliyuncs.com/TPO_Audio/tpo1/tpo1_listening_passage1_3.mp3";
        System.out.println(getSuffix(audioUrl));
    }

}
